<template>
  <el-dialog
    v-model="dialogVisible"
    title="管理员增加"
    width="70%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form ref="myForm" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :md="12" :lg="8">
          <el-form-item label="电话号码" prop="mobile">
            <el-input
              v-model.trim="formData.mobile"
              type="tel"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
        <el-col :md="12" :lg="8">
          <el-form-item label="姓名" prop="admin_name">
            <el-input v-model.trim="formData.admin_name" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :md="12" :lg="8">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model.trim="formData.password"
              maxlength="19"
              password
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button @click="handleClose(false)">关闭</el-button>
        <el-button type="primary" @click="handleInsert(myForm)">增加</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, reactive, watch, ref } from "vue";
import { ajax } from "@/util/request";
import md5 from "js-md5";
import type { FormInstance, FormRules } from "element-plus";

let updated: boolean = false;

let formData = reactive({
  password: "",
});
let myForm = ref<FormInstance>();

let rules = reactive<FormRules>({
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "手机号码必须是11位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 19, message: "请输入6到19位密码", trigger: "blur" },
  ],
  admin_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
});

let props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
});

watch(
  () => props.dialogVisible,
  (newVal) => {
    if (newVal && myForm.value) {
      myForm.value.resetFields();
      updated = false;
    }
  }
);

let emit = defineEmits();

/**
 * 关闭当前模态框
 * updated: 是否发生了数据变更
 */
function handleClose() {
  emit("close", updated);
}

function handleInsert(myForm: FormInstance) {
  myForm.validate((valid) => {
    if (!valid) {
      return;
    }
    let obj = { ...formData };
    obj.password = md5(obj.password);

    ajax("/admin/insert", obj).then((res) => {
      // 增加成功
      if (res.data.status > 0) {
        alert({ type: "success", message: "增加成功" });
        myForm.resetFields();
        updated = true;
      }
    });
  });
}
</script>

<style scoped>
</style>